import axios, { AxiosProgressEvent } from 'axios'

/**
 * 
 * @param url 下载文件链接
 * @param name 下载文件名称
 * @param callback 进度通知函数
 * @returns 
 */
export function basicDownload(url: string, name: string, callback?: Function) {
  return new Promise((resolve, reject) => {
    axios(url, {
      method: 'get',
      responseType: 'blob',
      onDownloadProgress: (evt: AxiosProgressEvent) => {
        if (typeof callback === 'function' && evt.total) {
          const progress = Math.floor((evt.loaded / evt.total) * 100)
          callback(progress)
          console.log('progress: ' + progress + '%')
        }
      }
    })
      .then((res) => {
        const blob = new Blob([res.data])
        const a = document.createElement('a')
        a.download = name
        a.href = URL.createObjectURL(blob)
        a.click()
        URL.revokeObjectURL(a.href)
        a.remove()
        resolve('下载完成')
      })
      .catch((err) => {
        reject(err)
      })
  })
}
